package service

import (
	"context"
	"duoke/model"
	"duoke/tables"
	"duoke/utils/gconv"
	"duoke/utils/orm"
	"duoke/utils/redislib"
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/gogf/gf/v2/os/gtime"
	"time"
)

var CourseProgress = new(courseProgressService)

type courseProgressService struct {
	TablesName string
}

func (s *courseProgressService) Save(req *tables.CourseProgress) error {
	var m tables.CourseProgress
	_, err := orm.Db.Where("user_id=? and from_id=?", req.UserId, req.FromId).Get(&m)
	if err != nil {
		return err
	}
	if m.LearningProgress >= req.LearningProgress {
		req.LearningProgress = m.LearningProgress
	}
	// 计算出至第一次已经多久
	unix := gtime.Now().Unix()
	redisKey := fmt.Sprintf("course_progress_%d_%d", req.UserId, req.FromId)
	// 判断key是否存在
	val := redislib.Redis.Get(context.Background(), redisKey).Val()
	// 不存在则记录,10分钟后过期
	redislib.Redis.Set(context.Background(), redisKey, unix, 6*time.Second)
	if val == "" {
		m.WatchTime += 0
	} else {
		// 存在则计算 过去多少秒
		unix -= gconv.Int64(val)
		m.WatchTime += float32(unix)
	}
	var u tables.User
	get, err := orm.Db.Where("id=?", req.UserId).Get(&u)
	if err != nil {
		return err
	}
	if !get {
		return errors.New("该用户不存在")
	}
	var m1 tables.CourseVideo
	where := orm.Db.Where("id=?", req.FromId)
	get, err = where.Get(&m1)
	if err != nil {
		return err
	}
	if !get {
		return errors.New("该课程不存在")
	}
	req.ListId = m1.ListId
	req.Acid = u.Acid
	req.SubMchId = m1.SubMchId
	req.State = 1
	if m.Id != 0 {
		req.Id = m.Id
		req.WatchTime = m.WatchTime
		_, err = orm.Db.Where("id=?", req.Id).Update(req)
		if err != nil {
			return err
		}
	} else {
		_, err = orm.Db.Insert(req)
		if err != nil {
			return err
		}
	}
	// 第一次观看 观看人数增加1
	m1.WatchTime = req.WatchTime
	if m.State == 0 {
		m1.NumberOfViews += 1
		_, err = orm.Db.Where("id=?", m1.ListId).Incr("number_of_learners", 1).
			Update(&tables.CourseList{})
	}
	_, err = where.Where("id=?", m1.Id).Update(&m1)
	return nil
}
func (s *courseProgressService) SaveWatch(c *gin.Context, req *model.ReqId) error {
	user, err := Request.User(c)
	if err != nil {
		return err
	}
	var m1 tables.CourseVideo
	get, err := orm.Db.Where("id=?", req.Id).Get(&m1)
	if err != nil || !get {
		return errors.New("视频不存在")
	}
	var m tables.CourseProgress
	get, err = orm.Db.Where("from_id=? and user_id=?", req.Id, user.Id).Get(&m)
	if err != nil {
		return err
	}
	m.WatchNumber += 1
	m.FromId = req.Id
	m.UserId = user.Id
	m.SubMchId = m1.SubMchId
	m.Acid = user.Acid
	m.ListId = m1.ListId
	if get {
		_, err = orm.Db.Where("from_id=? and user_id=?", req.Id, user.Id).Update(&m)
		if err != nil {
			return err
		}
	} else {
		_, err = orm.Db.Insert(&m)
		if err != nil {
			return err
		}
	}
	m1.WatchNumber += 1
	_, err = orm.Db.Where("id=?", req.Id).Update(&m1)
	return err
}
